const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const router = express.Router();

// 模拟用户数据库
const users = {};

// 定义上传目录
const uploadDir = path.join(__dirname, 'uploads');

// 确保上传目录存在
if (!fs.existsSync(uploadDir)) {
    fs.mkdirSync(uploadDir, { recursive: true });
}

// 配置 multer 存储引擎
const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, uploadDir);
    },
    filename: function (req, file, cb) {
        const userId = req.params.userId;
        const fileExtension = path.extname(file.originalname);
        const filename = `avatar-${userId}${fileExtension}`;
        cb(null, filename);
    }
});

// 创建 multer 实例
const upload = multer({ storage: storage });

// 上传头像接口
router.post('/users/:userId/avatar', upload.single('avatar'), (req, res) => {
    const userId = req.params.userId;
    if (!req.file) {
        return res.status(400).send('No avatar uploaded.');
    }
    // 更新用户的头像信息
    users[userId] = {
        ...users[userId],
        avatarPath: req.file.path
    };
    res.status(200).send({
        message: 'Avatar uploaded successfully',
        avatarPath: req.file.path
    });
});

// 获取用户信息接口
router.get('/users/:userId', (req, res) => {
    const userId = req.params.userId;
    const user = users[userId];
    if (!user) {
        return res.status(404).send('User not found.');
    }
    res.status(200).send({
        userId,
        avatarPath: user.avatarPath
    });
});

module.exports = router;